class CheckReg {

	regCheck(reg, msg, val) {
		if (!reg.test(val)) {
			alert(msg)
			return false;
		}
		return true;
	}

	checkUsername(val) {
		let reg = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
		let msg = "用户名必须以字母开头，只能包含字母、数字和下划线，长度5-16";
		return this.regCheck(reg, msg, val);
	}

	checkPassword(val) {
		let reg = /^[a-zA-Z]\w{5,17}$/;
		let msg = "密码必须以字母开头，只能包含字母、数字和下划线，长度6-18";
		return this.regCheck(reg, msg, val);
	}

	checkEmail(val) {
		let reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
		let msg = "邮箱格式错误";
		return this.regCheck(reg, msg, val);
	}

	checkAll(regname, regpwd, regemail) {
		let bool1 = this.checkUsername(regname);
		let bool2 = this.checkEmail(regemail);
		let bool3 = this.checkPassword(regpwd);
		return bool1 && bool2 && bool3;
	}
}


$(function () {

	var cr = new CheckReg();

	// 登录注册切换
	$('.img__btn').on('click', function () {
		$('.cont').toggleClass('s--signup');
	});

	// 登录
	$('#login-btn').on('click', function () {
		let username = $('#loginname').val();
		let password = $('#loginpwd').val();
		$.ajax({
			type: 'post',
			url: '/Discovery/login',
			data: {
				"username": username,
				"password": password
			},
			success: function (res) {
				if (res.msg == 1) {
					window.location.href = "/Discovery/index";
				} else {
					alert("用户名或密码错误");
				}
			}
		})
	});

	// 注册
	$('#reg-btn').on('click', function () {
		let username = $('#regname').val();
		let password = $('#regpwd').val();
		let email = $('#regemail').val();
		if (!cr.checkAll(username, password, email)) {
			return;
		}
		$.ajax({
			type: 'post',
			url: '/Discovery/reg',
			data: {
				"username": username,
				"password": password,
				"email": email
			},
			success: function (res) {
				if (res.msg) {
					$('.cont').toggleClass('s--signup');
				} else {
					alert("注册失败，请重试");
				}
			}
		})
	});

	// 查看登录名是否已被使用
	$('#regname').on('input', function () {
		let val = $(this).val();
		$.ajax({
			type: 'GET',
			url: '/Discovery/ajax/regname',
			data: {
				"regname": val
			},
			success: function (res) {
				if (res.count) {
					alert('用户名已被使用');
				}
			}
		})
	});

	// email 格式是否正确
	// $('#regemail').on('blur', () => { cr.checkEmail($(this).val()) });

	// 密码格式是否正确
	// $('#regpwd').on('blur', () => { cr.checkUsername($(this).val()) });

	// 用户名格式是否正确
	// $('#regname').on('blur', () => { cr.checkUsername($(this).val()) });

})